import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module/module_dapp/widgets/hover_status.dart';
import 'package:aichat_flutter_wallet/module/module_integral/model/integral_api.dart';
import 'package:aichat_flutter_wallet/module/module_trade/pages/trade_transactions.dart';
import 'package:aichat_flutter_wallet/module/module_trade/widgets/about_gas.dart';
import 'package:aichat_flutter_wallet/module_common/network/chains_type/ethchain.dart';
import 'package:aichat_flutter_wallet/module_common/provider/token_info_provider.dart';
import 'package:aichat_flutter_wallet/module_common/utils/auth.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/utils/sign.dart';
import 'package:aichat_flutter_wallet/module_common/utils/util.dart';
import 'package:aichat_flutter_wallet/module_common/network/http_chain_list.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/token_widget/token_logo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_language/lib_language.dart';
import 'package:lib_util/lib_util.dart';
import '../../mpc_help/mpcManager.dart';
import '../../provider/nav_key.dart';
import 'bottom_sheet_widget.dart';
import 'package:decimal/decimal.dart';

class TransferDialog extends StatefulWidget {
  final String? title;
  final Map<String, dynamic> transferDetails;
  final bool? twoBack;
  const TransferDialog({super.key, this.title, required this.transferDetails, this.twoBack = false});

  @override
  State<StatefulWidget> createState() {
    return _TransferDialogState();
  }
}

class _TransferDialogState extends State<TransferDialog> {
  String inputResult = '';
  int status = 1;

  @override
  void initState() {
    super.initState();
  }

  String gasFee() {
    final Token mainToken =widget.transferDetails['main'];
    return Utils.formatStringBalance(
        (BigInt.parse(widget.transferDetails['gas'].toString()) *
                BigInt.parse(widget.transferDetails['gasPrice'].toString()) /
                BigInt.from(10).pow(int.parse((mainToken.decimals).toString())))
            .toString(),
        fractionDigits: Config.balanceFixedNum,
        trimDecimalZero: true);
  }

  Widget confirmData() {
    return Column(
      children: [
        SizedBox(
          height: 10.w,
        ),
        Stack(
          clipBehavior: Clip.none,
          children: [
            TokenLogo(
              token: widget.transferDetails['token'],
              size: 40.w,
            ),
            Visibility(
                visible: widget.transferDetails['token'].contractType != TokenType.native.name,
                child: Positioned(
                  right: -3.w,
                  bottom: -1.w,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(18.w),
                    child:
                        PublicImage(width: 18.w, height: 18.w, image: widget.transferDetails['token'].getChain().logo),
                  ),
                ))
          ],
        ),
        SizedBox(
          height: 10.w,
        ),
        Text(
          '${widget.transferDetails['value']} ${widget.transferDetails['token'].symbol}',
          style: TextStyle(
            fontSize: 22.sp,
            fontWeight: FontWeight.bold,
            fontFamily: '_Din',
            color: AppColors.c_333333,
          ),
        ),
        SizedBox(
          height: 20.w,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              'Network',
              style: TextStyle(color: AppColors.c_868391, fontWeight: FontWeight.w400, fontSize: 13.sp),
            ),
            Text(
              widget.transferDetails['token'].getChain().name,
              style: TextStyle(color: AppColors.c_333333, fontWeight: FontWeight.w400, fontSize: 13.sp),
            ),
          ],
        ),
        SizedBox(
          height: 15.w,
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                RichText(
                  text: TextSpan(
                    children: [
                      TextSpan(
                        text: 'From',
                        style: TextStyle(color: AppColors.c_868391, fontWeight: FontWeight.w400, fontSize: 13.sp),
                      ),
                      // WidgetSpan(
                      //   child: SizedBox(width: 10), // 这里放置了一个SizedBox作为间隔
                      // ),
                      // TextSpan(
                      //   text: 'Wallet1',
                      //   style: TextStyle(color: AppColors.c_333333, fontWeight: FontWeight.w400, fontSize: 13),
                      // ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 6.w,
                ),
                Text(
                    Utils.formatAddress(
                      widget.transferDetails['from'],
                    ),
                    style: TextStyle(color: AppColors.c_333333, fontWeight: FontWeight.w400, fontSize: 13.sp)),
              ],
            ),
            Expanded(
                child: Image.asset(
              'assets/images/wallet-trade/trade.png',
              width: 31.w,
              height: 7.w,
              fit: BoxFit.fitHeight,
            )),
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                RichText(
                  text: TextSpan(
                    children: [
                      TextSpan(
                        text: 'To',
                        style: TextStyle(color: AppColors.c_868391, fontWeight: FontWeight.w400, fontSize: 13.sp),
                      ),
                      // WidgetSpan(
                      //   child: SizedBox(width: 10), // 这里放置了一个SizedBox作为间隔
                      // ),
                      // TextSpan(
                      //   text: 'Wallet2',
                      //   style: TextStyle(color: AppColors.c_333333, fontWeight: FontWeight.w400, fontSize: 13),
                      // ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 6.w,
                ),
                Text(
                    Utils.formatAddress(
                      widget.transferDetails['to'],
                    ),
                    style: TextStyle(color: AppColors.c_333333, fontWeight: FontWeight.w400, fontSize: 13.sp)),
              ],
            )
          ],
        ),
        SizedBox(
          height: 15.w,
        ),
        Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Row(
            children: [
              Text(
                'Gas Fee',
                style: TextStyle(color: AppColors.c_868391, fontWeight: FontWeight.w400, fontSize: 13.sp),
              ),
              SizedBox(
                width: 6.w,
              ),
              GestureDetector(
                onTap: () {
                  AboutGasDialog.showAboutGas(context, chainName: widget.transferDetails['token'].getChain().name);
                },
                child: Image.asset('assets/images/wallet-trade/tips-info.png',
                    width: 14.w, height: 14.w, fit: BoxFit.fitHeight),
              )
            ],
          ),
          RichText(
            text: TextSpan(
              children: [
                TextSpan(
                  text: '${gasFee()}  ${widget.transferDetails['main'].symbol}',
                  style: TextStyle(color: AppColors.c_333333, fontWeight: FontWeight.w400, fontSize: 13.sp),
                ),
                WidgetSpan(
                  child: SizedBox(width: 6.w), // 这里放置了一个SizedBox作为间隔
                ),
                TextSpan(
                  text:
                      '≈ \$${Utils.formatStringBalance((double.parse(gasFee()) * double.parse((widget.transferDetails['main']!.priceusd == null || widget.transferDetails['main']!.priceusd == '') ? '0' : widget.transferDetails['main']!.priceusd!)).toString(), fractionDigits: Config.priceNum)}',
                  style: TextStyle(color: AppColors.c_868391, fontWeight: FontWeight.w400, fontSize: 13.sp),
                ),
              ],
            ),
          ),
        ]),
        Visibility(
          visible: !(widget.transferDetails['token'].contract.isEmpty),
          child: Container(
            padding: EdgeInsets.only(top: 15.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  'Contract Address',
                  style: TextStyle(color: AppColors.c_868391, fontWeight: FontWeight.w400, fontSize: 13.sp),
                ),
                Text(
                  Utils.formatAddress(
                    widget.transferDetails['token'].contract,
                  ),
                  style: TextStyle(color: AppColors.c_333333, fontWeight: FontWeight.w400, fontSize: 13.sp),
                ),
              ],
            ),
          ),
        ),
        SizedBox(
          height: 30.w,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            HoverStatus(
              onPressed: () {
                Navigator.of(context).pop();
              },
              defaultColor: AppColors.c_F6F3FF,
              hoverColor: AppColors.c_F6F3FF,
              radius: 10.w,
              child: Container(
                width: 157.w,
                height: 46.w,
                alignment: Alignment.center,
                child: Text(
                  'Cancel',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                    color: AppColors.c_333333,
                  ),
                ),
              ),
            ),
            HoverStatus(
              onPressed: () {
                _sendTransaction();
              },
              defaultColor: AppColors.c_8667FE,
              hoverColor: AppColors.c_6D4DE7,
              radius: 10.w,
              child: Container(
                width: 157.w,
                height: 46.w,
                alignment: Alignment.center,
                child: Text(
                  'Confirm',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                    color: AppColors.c_white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget loadingSend() {
    return Container(
      height: 121.w,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.asset(
            'assets/images/common/loading2.gif',
            width: 100.w,
            height: 100.w,
          ),
        ],
      ),
    );
  }

  Widget pendSend(status) {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            height: 3.w,
          ),
          status
              ? Image.asset(
                  'assets/images/wallet-trade/trade-success-img.png',
                  width: 120.w,
                  height: 120.w,
                )
              : Image.asset(
                  'assets/images/wallet-trade/trade-error-img.png',
                  width: 120.w,
                  height: 120.w,
                ),
          SizedBox(
            height: 17.w,
          ),
          Text(
            status ? 'The Request is sent' : 'Transaction Canceled',
            style: TextStyle(color: AppColors.c_868391, fontSize: 12.sp, fontWeight: FontWeight.w400),
          ),
          SizedBox(
            height: 20.w,
          ),
          HoverStatus(
            radius: 10.w,
            defaultColor: AppColors.c_F6F3FF,
            hoverColor: AppColors.c_F6F3FF,
            onPressed: () {},
            child: Container(
              alignment: Alignment.center,
              height: 46.w,
              width: 335.w,
              child: Text(
                'OK',
                style: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.w500, color: AppColors.c_1D0061),
              ),
            ),
          )
        ],
      ),
    );
  }

  _sendTransaction() async {
    Chain chain = widget.transferDetails['token'].getChain()!;
    int chainId = chain.evmInfo!.chainId;
    Token token = widget.transferDetails['token'];
    String rpc = ObjectBox().nodeInfoModel.getSelectedNodeInfo(chain.shortName).url;
    // if (chain.type == ChainType.eth) {
      ETHTransaction ethTransaction = ETHTransaction(
        from: widget.transferDetails['from'],
        to: widget.transferDetails['to'],
        value: (Decimal.parse(widget.transferDetails['value']) *
                Decimal.parse((BigInt.from(10).pow(widget.transferDetails['token'].decimals)).toString()))
            .toString(),
        gas: widget.transferDetails['gas'].toString(),
        gasPrice: widget.transferDetails['gasPrice'].toString(),
        data: '',
        nonce: 0,
      );
      bool pass = await Authentication().startLocalAuth(
          showPasswordError: false,
          callBackError: () {
            Toast.hide();
            Toast.show(context,
                status: '0',
                position: Dpositon.top,
                message: "Verification password error",
                duration: Duration(milliseconds: 3000));
          });
      if (!pass) return;
      setState(() {
        status = 2;
      });
      Sign.EthSgin2(
        rpc,
        chainId,
        ethTransaction,
        token.contract,
        token.contractType,
      ).
      then((data) async {
        print('EthSgin2  $data');
        String? salt = await SP().getRandomSalt();
        if (salt == null) salt = await HttpChainList().getSaltByUrl();
        // 盐丢失
        if (salt == null) {
          Navigator.of(NavKey.getContext()).pop();
          return Toast.show(NavKey.getContext(),
              status: '2', position: Dpositon.top, message: 'Salt lost', duration: Duration(milliseconds: 2000));
        }
        List<String> keyList = await WalletCheck.checkSignKey();
        if (keyList.length < 2) {
          Navigator.of(NavKey.getContext()).pop();
          return Toast.show(NavKey.getContext(),
              status: '2',
              position: Dpositon.top,
              message: 'Please check wallet status',
              duration: Duration(milliseconds: 2000));
        }

        String signStr = '';
        if ([95279725].contains(chainId)) {
          // 重铸 之后 使用签名失败
          signStr=await mpcTool().solSignTx(data['tx'], keyList[0], keyList[1], salt);
        }else{
          signStr=await mpcTool().signTx(data['tx'], keyList[0], keyList[1], salt);
        }
        if (signStr == 'invalid padding' || signStr == '') {
          Navigator.of(NavKey.getContext()).pop();
          return Toast.show(NavKey.getContext(),
              status: '2', position: Dpositon.top, message: 'Signature failed', duration: Duration(milliseconds: 2000));
        }
        Sign.SingSend(rpc, chainId, data['tran'], signStr, true).then((txId) {
          IntegralApi.getUserTaskUpdate(taskType: TaskType.DailyTasks, taskCode: 306);
          if (Utils.isNotEmpty(txId)) {
            kaiPrint('++++++++++++++');
            kaiPrint('txId ++++++++++++++  : $txId');
            //加入缓存之中
            Provider.of<TokenInfoNotifier>(NavKey.getContext(), listen: false).insertTransaction(
                  txId,
                  token,
                  widget.transferDetails['to'],
                  widget.transferDetails['value'],
                );
          }
          Navigator.of(NavKey.getContext()).pop();
          if (widget.twoBack!) {
            Navigator.of(NavKey.getContext()).pop(token);
          } else {
            Navigator.of(NavKey.getContext()).pop();
            Navigator.of(NavKey.getContext()).push(MaterialPageRoute(builder: (_) {
              return TradeTransactionsPage(
                contract: token.contract.length > 0 ? token.contract : '',
                contractType: token.contractType,
                token: token,
              );
            }));
          }
        }).catchError((e) {
          kaiPrint("catchError :::::+++++++++++++++++++++++++ ${e.toString()}");
          Log.logger.e(e);
          _onErrorCallback(e);
        });
      }).catchError((e) {
        Log.logger.e(e);
        _onErrorCallback(e);
      });
    // }
  }

  _onErrorCallback(e) {
    Navigator.of(NavKey.getContext()).pop();
    Toast.show(NavKey.getContext(),
        status: '2', position: Dpositon.top, message: e.toString(), duration: Duration(milliseconds: 2000));
  }

  @override
  Widget build(BuildContext context) {
    return BottomSheetWidget(
      title: widget.title ?? LocaleKeys.qingshuruqianbaomima.tr(),
      showCloseBtn: status != 2,
      expand: false,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        child: Column(
          children: [
            Visibility(visible: status == 1, child: confirmData()),
            Visibility(visible: status == 2, child: loadingSend()),
            Visibility(visible: status == 3, child: pendSend(true)),
            Visibility(visible: status == 4, child: pendSend(false)),
            SizedBox(
              height: 10 + MediaQuery.of(context).padding.bottom,
            ),
          ],
        ),
      ),
    );
  }
}
